--- title: "填涂颜色" created: 2025-11-28 tags: - 算法 --- # 填涂颜色 ## 题目 [填涂颜色](https://www.luogu.com.cn/problem/P1162) ![[image-0f5655e5.png]] ## 思路分析 ![[image-f443ec2c.png]] ![[image-6b171ee2.png]] 即使圈长这样 也只需要一桶油漆就可以标记出来 ```cpp #include using namespace std; #define endl '\n' typedef pair PII; const int N=35; int g[N][N]; bool st[N][N]; int n; int dx[4]={-1,0,1,0}; int dy[4]={0,1,0,-1}; bool isVaild(int x,int y){ return x>=0 && x<=n-1 && y>=0 && y<=n-1 && !st[x][y]; } void bfs(int x,int y){ queue q; q.push({x,y}); st[x][y]=true; while(!q.empty()){ auto cur=q.front();q.pop(); int ux=cur.first,uy=cur.second; for(int i=0;i<4;i++){ int nx=ux+dx[i],ny=uy+dy[i]; if(isVaild(nx,ny) && g[nx][ny]==0){ q.push({nx,ny}); st[nx][ny]=true; } } } } int main() { ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); cin>>n; for(int i=0;i>g[i][j]; } } bfs(0,0); for(int i=0;i using namespace std; #define endl '\n' typedef pair PII; const int N=35; int g[N][N]; bool st[N][N]; int n; int dx[4]={-1,0,1,0}; int dy[4]={0,1,0,-1}; bool isVaild(int x,int y){//整个加一圈 数据在1~n 加上一圈0~n+1 return x>=0 && x<=n+1 && y>=0 && y<=n+1 && !st[x][y]; } void bfs(int x,int y){ queue q; q.push({x,y}); st[x][y]=true; while(!q.empty()){ auto cur=q.front();q.pop(); int ux=cur.first,uy=cur.second; for(int i=0;i<4;i++){ int nx=ux+dx[i],ny=uy+dy[i]; if(isVaild(nx,ny) && g[nx][ny]==0){ q.push({nx,ny}); st[nx][ny]=true; } } } } int main() { ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); cin>>n; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ cin>>g[i][j]; } } bfs(0,0); for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(g[i][j]==0 && !st[i][j]){ g[i][j]=2; } } } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ cout<